import type { ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import type {
  AddPermissionBean,
  PermissionItem,
  UpdatePermissionBean,
} from '@/pages/Auth/AuthPermission/data';
import { request } from 'umi';
import { message } from 'antd';

/**
 * 分页查询权限
 * @param params
 */
export async function pageQueryPermissionList(params: {
  id?: string,
  name?: string,
  type?: number,
  page?: number,
  pageSize?: number,
}): Promise<RequestData<PermissionItem>> {
  try {
    const res: ResponsePaginationData<PermissionItem> = await request('/permission/query', {
      params: {
        page: 1,
        pageSize: 10,
        ...params,
      }
    });

    if (res?.code !== SUCCESS_CODE) {
      return { success: false, total: 0, data: [] };
    }

    return {
      success: res.code === SUCCESS_CODE,
      total: res.data?.total,
      data: res.data?.list,
    };
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 添加自定义权限
 * @param params
 */
export async function addPermission(data: AddPermissionBean) {
  try {
    const res = request('/permission/add', {
      method: 'POST',
      data: data,
    });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 修改权限
 * @param params
 */
export async function editPermission(data: UpdatePermissionBean): Promise<RequestData<any>> {
  try {
    const res = request(`/permission/update`, {
      method: 'POST',
      data: data,
    });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 删除自定义权限
 * @param params
 */
export async function deletePermission(id: string) {
  try {
    const res = await request('/permission/delete', {
      method: 'POST',
      data: {
        id: id
      },
    });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}
